import { ref, computed, reactive } from "vue";
import { logout, rePassWord } from "~/api/manger";
import { toast, showModal } from "~/composables/util";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
export function useRepassword() {
  const router = useRouter();
  const store = useStore();
  const ruleFormRef = ref(null);
  const ruleForm = reactive({
    oldpassword: "",
    password: "",
    repassword: "",
  });
  const formDrawer = ref(null);
  const rules = {
    oldpassword: [
      { required: true, message: "旧密码不可为空", trigger: "blur" },
    ],
    password: [{ required: true, message: "新密码不可为空", trigger: "blur" }],
    repassword: [
      { required: true, message: "确认新密码不可为空", trigger: "blur" },
    ],
  };
  // 修改密码
  const submitForm = () => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) return false;
      formDrawer.value.showLoading();
      rePassWord(ruleForm)
        .then((res) => {
          toast("密码修改成功,请重新登录", "success");
          store.dispatch("logout");
          router.push("/Login");
        })
        .finally(() => {
          formDrawer.value.hideLoading();
        });
    });
  };
  const openRepasswordForm = () => {
    formDrawer.value.open();
  };

  return {
    ruleFormRef,
    ruleForm,
    formDrawer,
    rules,
    submitForm,
    openRepasswordForm,
  };
}
export function useLogout() {
  const router = useRouter();
  const store = useStore();
  function handlelogout() {
    showModal("是否退出登录?")
      .then(() => {
        logout().finally(() => {
          store.dispatch("logout");
          router.push("/Login");
          toast("退出成功");
        });
      })
      .catch(() => {
        toast("取消退出", "info");
      });
  }
  return {
    handlelogout,
  };
}
